import * as THREE from 'three'
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'

let scene = new THREE.Scene()
scene.background = new THREE.CubeTextureLoader()
    .setPath('./images/')
    .load([
        'px.jpg', 'nx.jpg', 'py.jpg', 'ny.jpg', 'pz.jpg', 'nz.jpg'
    ])
let camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    1,
    100000
)
camera.position.z = 20
let renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setPixelRatio(window.devicePixelRatio)
document.body.appendChild(renderer.domElement)
let control = new OrbitControls(camera, renderer.domElement)

//星星
let objects = []
let textureload = new THREE.TextureLoader()
for (let i = 0; i < 300; i++) {
    let mat = new THREE.SpriteMaterial({
        map: textureload.load('./images/2.png'),
        transparent: true
    })
    let mesh = new THREE.Sprite(mat)
    let r = Math.random()
    mesh.position.y = Math.random() * 100 + 250
    mesh.position.x = Math.random() * 1000 - 500
    mesh.position.z = Math.random() * 1000 - 500
    mesh.scale.x = r * 6 + 5
    mesh.scale.y = r * 6 + 5
    mesh.scale.z = r * 6 + 5
    scene.add(mesh)
    objects.push({
        mesh,
        opacity: r * 0.005,
        rotate: r * 0.05
    })
}

//流星
let metorGeo = new THREE.CylinderGeometry(0, 0.3, 40, 80);
let metorMat = new THREE.MeshBasicMaterial({
    color: 0xffffff,
    map: textureload.load('./images/3.png')
})
let metor = new THREE.Mesh(metorGeo, metorMat)
metor.position.y = 200;
metor.scale.set(2, 2, 4)
scene.add(metor)

function ani() {
    requestAnimationFrame(ani)
    renderer.render(scene, camera)
    control.update()
    //让流星动起来
    metor.position.z -= 7;
    if (metor.position.z < -600) {
        metor.position.z = Math.random() * 100 - 200
    }
    //让星星动起来
    for (let i = 0; i < objects.length; i++) {
        let index = objects[i]
        if (index.mesh.material.opacity < 0) {
            index.mesh.material.opacity = 1
        }
        index.mesh.material.opacity -= index.opacity
        index.mesh.material.rotation -= index.rotate
    }
}
ani()